package cn.dujc.superkid.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.universalvideoview.UniversalMediaController;
import com.universalvideoview.UniversalVideoView;


import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import cn.dujc.core.util.ToastUtil;
import cn.dujc.superkid.R;
import cn.dujc.superkid.URLImageParser;
import cn.dujc.superkid.adapter.Fragement_testAdapter;
import cn.dujc.superkid.api.HttpHelper;
import cn.dujc.superkid.api.QMap;
import cn.dujc.superkid.api.Result;
import cn.dujc.superkid.api.ResultCallBack;
import cn.dujc.superkid.bean.CupListResult;
import cn.dujc.superkid.bean.MessageEntity;
import cn.dujc.superkid.bean.RecordBean;
import cn.dujc.superkid.bean.RegisterResult;
import cn.dujc.superkid.bean.VideoListResult;
import cn.dujc.superkid.fragment.MyLessonVideo.ChapterFragment;
import cn.dujc.superkid.fragment.MyLessonVideo.ExercisesFragment;
import cn.dujc.superkid.fragment.MyLessonVideo.ReplyFragment;
import cn.dujc.superkid.fragment.cup.CupChapterFragment;
import cn.dujc.superkid.fragment.cup.CupExercisesFragment;
import cn.dujc.superkid.fragment.cup.CupReplyFragment;
import cn.dujc.superkid.utils.Preferences;


/**
 * @author du
 *         date 2018/8/4 下午9:12
 */
public class CupVideoActivity extends AppCompatActivity implements UniversalVideoView.VideoViewCallback, View.OnClickListener, View.OnTouchListener, View.OnLayoutChangeListener, TextWatcher {

    private View videoLayout;
    private View bottomLayout;
    private UniversalVideoView videoView;
    private UniversalMediaController mediaController;
    private int seekPosition;//当前进度
    private int cachedHeight;//视频区域大小
    private boolean isFullscreen;//是否全屏;
    private static final String SEEK_POSITION_KEY = "SEEK_POSITION_KEY";//用于保存seekPosition的key值
    private static final String TAG = CupVideoActivity.class.getName();
    public String video_id;
    private String course_id;
    private CupListResult Data;
    private TextView videoname;
    private TextView videodecrsp;
    private ImageView joinmylesson;
    private ImageView finishedvideo;
    private TextView joinmylesson_text;
    private TabLayout tabLayout;
    private View liuyan_group;
    private ViewPager vp_pager;
    private List<String> titles = new ArrayList<>();
    private TextView finishStudy;
    private View addLiuyan;
    private EditText liuyan_edit;
    private int keyHeight = 0;
    private TextView liuyan_submit;
    private List<Fragment> fragments;
    private ImageView videoFrame;
    private String videoTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coursevideo);
        Intent intent = getIntent();
        videoTitle=intent.getStringExtra("videoTitle");
        video_id = intent.getStringExtra("video_id");
        course_id = intent.getStringExtra("course_id");
        Log.d(TAG, "onCreate: course_id=" + course_id);
        int screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
        keyHeight = screenHeight / 3;
        initResult();
        initView();
        loaddata();
        intiEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        findViewById(R.id.activity_coursevideo_group).addOnLayoutChangeListener(this);
    }

    private void initResult() {
    }

    private void loaddata() {
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(CupVideoActivity.this);
        HttpHelper.getCourse().cupList(QMap.build()
                .put("user_id", loginResult.getUid())
                .put("channel", Preferences.getInstance().getChannel(CupVideoActivity.this).getChannel_id())
                .put("cup_id", course_id)
                .put("logincode", loginResult.getLogincode())
                .put("video_id", video_id)
                .create()).enqueue(new ResultCallBack<Result<CupListResult>>(CupVideoActivity.this) {
            @Override
            public void onSuccessCallback(int code, Result<CupListResult> body) {
                if (body != null) {
                    final CupListResult data = body.getData();
                    fragments = new ArrayList<>();
                    Data = data;
                    if (data != null) {
                        final List<CupListResult.VideoBean> video = data.getVideo();
                        List<CupListResult.VideoMessageBean> messageEn = data.getVideo_message();
                        ImageLoader imageLoader = ImageLoader.getInstance();//ImageLoader需要实例化
                        imageLoader.init(ImageLoaderConfiguration.createDefault(CupVideoActivity.this));
                        URLImageParser imageGetter = new URLImageParser(videodecrsp);
                        videodecrsp.setText(Html.fromHtml(data.getVideo_describe(), imageGetter, null));
                        toData(data);
                        saveDataToDB(data);
                        if (data.getJoin_my_course() == 2) {
                            joinmylesson.setAlpha((float) 0.3);
                            joinmylesson_text.setTextColor(Color.parseColor("#888888"));
                        } else {
                            joinmylesson.setAlpha((float) 1);
                            joinmylesson_text.setTextColor(Color.parseColor("#222222"));
                        }
                        if (Data.getVideo().get(getCurrentPosition()).getIs_learn() == 1) {
                            finishStudy.setText("完成该学习");
                        } else {
                            finishStudy.setText("取消完成该学习");
                        }
                        titles.add("练习题");
                        titles.add("章节");
                        titles.add("问答");
                        for (int i = 0; i < titles.size(); i++) {
                            tabLayout.addTab(tabLayout.newTab().setText(titles.get(i)));
                        }
                        final CupExercisesFragment exercisesFragment = new CupExercisesFragment();
                        final CupChapterFragment chapterFragment = new CupChapterFragment();
                        final CupReplyFragment replyFragment = new CupReplyFragment();
                        List<CupListResult.ExamineListBean> exercisesEntityList = data.getExamine_list();
                        Bundle bundle = new Bundle();
                        bundle.putParcelableArrayList("list", (ArrayList<? extends Parcelable>) exercisesEntityList);
                        exercisesFragment.setArguments(bundle);
                        Bundle bundle1 = new Bundle();

                        bundle1.putParcelableArrayList("list2", (ArrayList<? extends Parcelable>) video);
                        bundle1.putString("video_id", video_id);
                        bundle1.putString("course_id", course_id);
                        chapterFragment.setArguments(bundle1);
                        Bundle bundle2 = new Bundle();
                        bundle2.putParcelableArrayList("list3", (ArrayList<? extends Parcelable>) messageEn);
                        replyFragment.setArguments(bundle2);
                        fragments.add(exercisesFragment);
                        fragments.add(chapterFragment);
                        fragments.add(replyFragment);
                        Log.i(TAG, "=====size=========caizhijia1======CourseVideoActivity=====" + fragments.size());

                        Fragement_testAdapter fragementAdapter = new Fragement_testAdapter(getSupportFragmentManager(), fragments, titles);
                        vp_pager.setAdapter(fragementAdapter);
                        vp_pager.setCurrentItem(0);
                        tabLayout.setupWithViewPager(vp_pager);

                        Log.i(TAG, "==============caizhijia1======CourseVideoActivity=====" + data.getJoin_my_course());
                    }
                }
            }
        });
    }


    private void saveDataToDB(CupListResult data) {
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(this);
        String uid = loginResult.getUid();
        List<RecordBean> datas = DataSupport.where("userid=?", uid).where("video_id=?", video_id).find(RecordBean.class);
        if (datas.size() == 0) {
            RecordBean recordBean = new RecordBean(3, data.getTitle(), videoTitle, video_id, course_id, uid);
            recordBean.save();
        }
    }

    private int getCurrentPosition() {
        int pos = 0;
        for (pos = 0; pos < Data.getVideo().size(); pos++) {
            if ((Data.getVideo().get(pos).getId() + "").equals(video_id)) {
                return pos;
            }
        }
        return 0;
    }

    private void loadTag() {
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(CupVideoActivity.this);
        HttpHelper.getCourse().videoLearning(QMap.build()
                .put("user_id", loginResult.getUid())
                .put("channel", Preferences.getInstance().getChannel(CupVideoActivity.this).getChannel_id())
                .put("course_id", course_id)
                .put("video_id", video_id)
                .put("logincode", loginResult.getLogincode())
                .put("type_id", 2)
                .create()).enqueue(new ResultCallBack<Result<Object>>(CupVideoActivity.this) {
            @Override
            public void onSuccessCallback(int code, Result<Object> body) {
                String msg = body.getMsg();
                ToastUtil.showToast(CupVideoActivity.this, msg);
                if (msg.equals("标记成功！")) {
                    finishStudy.setText("取消完成该学习");
                } else {
                    finishStudy.setText("完成该学习");
                }
            }
        });
    }


    private void submitMessage() {
        final String msg = liuyan_edit.getText().toString();
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(CupVideoActivity.this);
        HttpHelper.getCourse().cupMessage(QMap.build()
                .put("user_id", loginResult.getUid())
                .put("channel", Preferences.getInstance().getChannel(CupVideoActivity.this).getChannel_id())
                .put("cup_video_id", video_id)
                .put("logincode", loginResult.getLogincode())
                .put("content", liuyan_edit.getText().toString())
                .create()).enqueue(new ResultCallBack<Result<Object>>(CupVideoActivity.this) {
            @Override
            public void onSuccessCallback(int code, Result<Object> body) {
                hideKeyboard();
                liuyan_edit.setText("");
                ToastUtil.showToast(CupVideoActivity.this, body.getMsg());
                loaddata();
            }
        });
    }

    private void videoCourse() {
        final RegisterResult loginResult = Preferences.getInstance().getLoginResult(CupVideoActivity.this);
        HttpHelper.getCourse().videoCourse(QMap.build()
                .put("user_id", loginResult.getUid())
                .put("channel", Preferences.getInstance().getChannel(CupVideoActivity.this).getChannel_id())
                .put("course_id", course_id)
                .put("logincode", loginResult.getLogincode())
                .put("type", 2)
                .create()).enqueue(new ResultCallBack<Result<Object>>(CupVideoActivity.this) {
            @Override
            public void onSuccessCallback(int code, Result<Object> body) {
                ToastUtil.showToast(CupVideoActivity.this, body.getMsg());
                Data.setJoin_my_course(2);
                joinmylesson_text.setTextColor(Color.parseColor("#888888"));
//                Data.set
            }
        });
    }

    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(liuyan_edit.getWindowToken(), 0);
    }

    private void toData(CupListResult data) {
        videoname.setText(data.getTitle());
        videoView.setVideoPath(data.getUcloud_video_url());
        Glide.with(this).load(data.getUcloud_video_pic()).into(videoFrame);
    }


    /**
     * 初始化控件
     */
    private void initView() {
        videoFrame = findViewById(R.id.video_1_frame);
        liuyan_submit = findViewById(R.id.liuyan_submit);
        liuyan_submit.setOnClickListener(this);
        liuyan_edit = findViewById(R.id.liuyan_edit);
        liuyan_edit.addTextChangedListener(this);
        addLiuyan = findViewById(R.id.tian_jia_liu_yan);
        liuyan_group = findViewById(R.id.liuyan_group);
        videoLayout = findViewById(R.id.videoLayout);
        finishStudy = findViewById(R.id.coursevideo_finish_video_study);
        finishStudy.setOnClickListener(this);
        addLiuyan.setOnClickListener(this);
        bottomLayout = findViewById(R.id.bottomLayout);
        videoView = (UniversalVideoView) findViewById(R.id.videoView);
        mediaController = (UniversalMediaController) findViewById(R.id.mediaController);
        videoname = findViewById(R.id.lessonname);
//        Log.i(TAG,"==============caizhijia1==url====CourseVideoActivity=====" + mVideoUriPath);
        videodecrsp = findViewById(R.id.videodecrsp);
        joinmylesson = findViewById(R.id.joinmylesson);
        joinmylesson_text = findViewById(R.id.joinmylesson_text);
        joinmylesson_text.setOnClickListener(this);
        finishedvideo = findViewById(R.id.finishedvideo);
        tabLayout = findViewById(R.id.tablayout);
        vp_pager = findViewById(R.id.tab_viewpager);

//        finishedvideo.setOnClickListener(this);
//        if (is_learn.equals("1")) {
//            finishedvideo.setAlpha((float) 1);
//        } else {
//            finishedvideo.setAlpha((float) 0.3);
//        }
        addLiuyan.setOnTouchListener(this);

    }

    private void intiEvent() {
//把视频控制的按钮设置到播放器里
        videoView.setMediaController(mediaController);
//设置置视频区域大小
        setVideoAreaSize();
//设置屏幕状态和播放状态的监听
        videoView.setVideoViewCallback(this);
    }

    /**
     * 设置置视频区域大小和播放地址
     */
    private void setVideoAreaSize() {
        videoLayout.post(new Runnable() {
            @Override
            public void run() {
                int width = videoLayout.getWidth();
                cachedHeight = (int) (width * 405f / 720f);
// cachedHeight = (int) (width * 3f / 4f);
// cachedHeight = (int) (width * 9f / 16f);
                ViewGroup.LayoutParams videoLayoutParams = videoLayout.getLayoutParams();
                videoLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                videoLayoutParams.height = cachedHeight;
                videoLayout.setLayoutParams(videoLayoutParams);

                videoView.requestFocus();
            }
        });
    }


//--------------重写下面三个方面是为了保存seekPosition--------------

    @Override
    protected void onPause() {
        super.onPause();
        if (videoView != null && videoView.isPlaying()) {
            seekPosition = videoView.getCurrentPosition();
            Log.i("info", "onPause mSeekPosition=" + seekPosition);
            videoView.pause();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.i("info", "onSaveInstanceState Position=" + videoView.getCurrentPosition());
        outState.putInt(SEEK_POSITION_KEY, seekPosition);
    }

    @Override
    protected void onRestoreInstanceState(Bundle outState) {
        super.onRestoreInstanceState(outState);
        seekPosition = outState.getInt(SEEK_POSITION_KEY);
        Log.i("info", "onRestoreInstanceState Position=" + seekPosition);
    }


//--------------以下方法都是VideoViewCallback接口的实现方法--------------


    @Override
    public void onScaleChange(boolean isFullscreen) {
        this.isFullscreen = isFullscreen;
        if (isFullscreen) {
            ViewGroup.LayoutParams layoutParams = videoLayout.getLayoutParams();
            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
            videoLayout.setLayoutParams(layoutParams);
//设置全屏时,无关的View消失,以便为视频控件和控制器控件留出最大化的位置
            bottomLayout.setVisibility(View.GONE);

        } else {
            ViewGroup.LayoutParams layoutParams = videoLayout.getLayoutParams();
            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            layoutParams.height = this.cachedHeight;
            videoLayout.setLayoutParams(layoutParams);
            bottomLayout.setVisibility(View.VISIBLE);
        }

        switchTitleBar(!isFullscreen);
    }

    /**
     * 横竖屏切换的时候控制ActionBar的状态
     *
     * @param show
     */
    private void switchTitleBar(boolean show) {
        android.support.v7.app.ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            if (show) {
                supportActionBar.show();
            } else {
                supportActionBar.hide();
            }
        }
    }

    @Override
    public void onPause(MediaPlayer mediaPlayer) {// 视频暂停
        Log.i("info", "onPause");
    }

    @Override
    public void onStart(MediaPlayer mediaPlayer) {// 视频开始播放或恢复播放
        Log.i("info", "onStart");
        videoFrame.setVisibility(View.GONE);
    }

    @Override
    public void onBufferingStart(MediaPlayer mediaPlayer) {// 视频开始缓冲
        Log.i("info", "onBufferingStart");
    }

    @Override
    public void onBufferingEnd(MediaPlayer mediaPlayer) {// 视频结束缓冲
        Log.i("info", "onBufferingEnd");
    }

    @Override
    public void onBackPressed() {
        if (this.isFullscreen) {
            videoView.setFullscreen(false);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onClick(View v) {
        if (v == finishStudy) {
            if (Data != null) {
                loadTag();
            }
        } else if (v == addLiuyan) {
            liuyan_group.setVisibility(View.VISIBLE);
            liuyan_edit.setFocusable(true);
            liuyan_edit.setFocusableInTouchMode(true);
            liuyan_edit.requestFocus();
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(liuyan_edit, InputMethodManager.SHOW_FORCED);
        } else if (liuyan_submit == v) {
            if (liuyan_edit.getText().length() > 0) {
                submitMessage();
            }
        } else if (joinmylesson_text == v) {
            if (Data != null) {
                if (Data.getJoin_my_course() != 2) {
                    videoCourse();
                }
            }
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return false;
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
            liuyan_group.setVisibility(View.GONE);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() == 0) {
            liuyan_submit.setTextColor(Color.parseColor("#888888"));
        } else {
            liuyan_submit.setTextColor(Color.parseColor("#222222"));
        }
    }
}

